package com.example.feidaolumanager.pages.ui.task

import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Photo
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import coil.compose.AsyncImage
import com.example.feidaolumanager.api.ApiService
import com.example.feidaolumanager.pages.ui.task.ui.theme.FeidaoluManagerTheme
import com.example.feidaolumanager.pojo.RectificationTasks
import com.example.feidaolumanager.pojo.Task
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.viewModel.FileUploadViewModel
import java.text.SimpleDateFormat
import java.util.Date

class RectificationResultsActivity : ComponentActivity() {
    private val TAG: String = this.toString()

    private var ifShowLargeImage: MutableState<Boolean> = mutableStateOf(false)


    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val taskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]

        val task: Task? = intent.getSerializableExtra("task") as Task?
        val user: User = intent.getSerializableExtra("user") as User

        taskViewModel.updateResponse.observe(this) {
            if (it.code == 1) {
                Toast.makeText(this, "提交成功", Toast.LENGTH_SHORT).show()
                taskViewModel.getTask(user)
                setResult(RESULT_OK, null)
                finish()
            }
        }

        Log.e(TAG, "onCreate: $task")

        val checkedList = task?.cy?.split(",") ?: listOf()

        val picture = task?.purl?.split(",")
        val pictureEndUrl = task?.purlEnd?.split(",")

        // 当前上传的照片是那一项的
        var currentSelectedImageForWho = 0

        if (checkedList.size > 1) {
            checkedList.forEach {
                var cur: Int
                try {
                    cur = it.toInt()
                } catch (e: Exception) {
                    Log.e(TAG, "onCreate: ${task?.cy},${checkedList.size}")
                    cur = 1
                }
                RectificationTasks.defineTask[cur].picture.value =
                    picture?.get(cur - 1) ?: ""
                RectificationTasks.defineTask[cur].pictureEnd.value =
                    pictureEndUrl?.get(cur - 1) ?: ""

                RectificationTasks.defineTask[cur].checked.value = true
            }
        }

        val fileUploadViewModel = ViewModelProvider(this).get(FileUploadViewModel::class.java)


        setContent {
            FeidaoluManagerTheme {

                var largeImageUrl by remember {
                    mutableStateOf("")
                }

                val launcher =
                    rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->

                        // TODO: 上传选择的图片到服务器

                        if (uri != null) {
                            // 获取选择的图片的输入流
                            val inputStream = this.contentResolver.openInputStream(uri)
                            // 获取选择图片的类型: "image/jpeg"
                            val type = this.contentResolver.getType(uri)
                            Log.e(TAG, "onCreate: $type")

                            val imageBytes = inputStream?.readBytes()
                            inputStream?.close()
                            if (imageBytes != null) {
                                fileUploadViewModel.fileUpload(
                                    imageBytes, type?.replace("/", ".")
                                )
                            }
                        }
                    }

                fileUploadViewModel.uploadImagePath.observe(this) {
                    // 在这里处理选择的图片
                    val tasks = RectificationTasks.defineTask.get(currentSelectedImageForWho / 2)

                    // 偶数是整改前
                    if (currentSelectedImageForWho % 2 == 0) {

                        tasks.picture.value = it ?: ""
                    } else {
                        tasks.pictureEnd.value = it ?: ""
                    }
                }

                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {

                    if (ifShowLargeImage.value) {
                        Column {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.End,
                            ) {
                                Icon(imageVector = Icons.Default.Close,
                                    contentDescription = "关闭全屏显示图片的按钮",
                                    modifier = Modifier
                                        .clickable {
                                            ifShowLargeImage.value = false
                                        }
                                        .size(30.dp),
                                    tint = Color.Black)
                            }

                            AsyncImage(
                                model = largeImageUrl,
                                contentDescription = "机械图片",
                                modifier = Modifier.fillMaxSize()
                            )
                        }

                    } else {
                        Scaffold(topBar = {
                            TopAppBar(
                                title = {
                                    Text(text = "工地整改结果", color = Color.White)
                                }, navigationIcon = {
                                    Icon(imageVector = Icons.Default.ArrowBack,
                                        contentDescription = "返回上一级",
                                        tint = Color.White,
                                        modifier = Modifier.clickable { finish() })
                                }, colors = TopAppBarDefaults.smallTopAppBarColors(
                                    containerColor = Color(0, 179, 98)
                                )
                            )
                        }) { paddingValues ->

                            var ifHaveOtherReason by remember {
                                mutableStateOf(task?.bz?.isNotEmpty() ?: false)
                            }




                            Column(
                                modifier = Modifier
                                    .padding(paddingValues = paddingValues)
                                    .background(color = Color(246, 246, 246))
                                    .verticalScroll(state = rememberScrollState())
                            ) {

                                Column(
                                    modifier = Modifier
                                        .padding(all = 10.dp)
                                        .clip(
                                            RoundedCornerShape(10.dp)
                                        )
                                        .background(color = Color.White)
                                ) {
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(all = 10.dp),
                                    ) {
                                        Text(text = task!!.name)
                                    }

                                    Divider()
                                    Row(verticalAlignment = Alignment.CenterVertically) {
                                        Spacer(modifier = Modifier.width(10.dp))
                                        Image(
                                            imageVector = Icons.Default.AccountCircle,
                                            contentDescription = "头像图标",
                                            modifier = Modifier.size(50.dp)
                                        )

                                        Spacer(modifier = Modifier.width(10.dp))

                                        Column {

                                            Row(verticalAlignment = Alignment.CenterVertically) {
                                                Text(
                                                    text = listOf(
                                                        "施工方",
                                                        "街道办",
                                                        "住建局",
                                                        "环保局"
                                                    )[user.level - 1],
                                                    modifier = Modifier
                                                        .clip(RoundedCornerShape(4.dp))
                                                        .background(color = Color(179, 225, 157))
                                                        .border(1.dp, color = Color(0, 179, 98)),
                                                    color = Color(0, 179, 98),
                                                    fontSize = 12.sp
                                                )
                                                Text(text = user.name)
                                            }


                                            Text(
                                                text = task!!.userid, fontSize = 14.sp,
                                                color = Color.Gray
                                            )
                                        }
                                    }
                                    Divider()
                                    Row(
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(all = 10.dp)
                                    ) {
                                        Text(
                                            text = "预警时间", fontWeight = FontWeight.Normal,
                                            color = Color.DarkGray,
                                            fontSize = 14.sp
                                        )
                                        Text(
                                            text = task!!.addtime, fontWeight = FontWeight.Normal,
                                            color = Color.DarkGray,
                                            fontSize = 14.sp
                                        )
                                    }
                                }


                                // 显示6个整改项目
                                RectificationTasks.defineTask.forEachIndexed { index, rectificationTask ->

                                    var itemHeight by remember {
                                        if (rectificationTask.checked.value)
                                            mutableIntStateOf(140)
                                        else
                                            mutableIntStateOf(90)
                                    }

                                    Column(
                                        modifier = Modifier
                                            .padding(all = 10.dp)
                                            .clip(RoundedCornerShape(6.dp))
                                            .background(color = Color.White)
                                    ) {
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Text(text = rectificationTask.title)
                                            Checkbox(
                                                checked = rectificationTask.checked.value,
                                                onCheckedChange = {
                                                    rectificationTask.checked.value = it
                                                    itemHeight = if (it) 140 else 100
                                                },
                                            )
                                        }


                                        if (rectificationTask.checked.value) {
                                            Divider()
                                            Text(
                                                text = "整改前的图片:", fontSize = 14.sp,
                                                modifier = Modifier.padding(4.dp)
                                            )
                                            if (rectificationTask.picture.value.isEmpty()) {
                                                Icon(imageVector = Icons.Default.Photo,
                                                    tint = Color.Gray,
                                                    contentDescription = "选择图片上传按钮",
                                                    modifier = Modifier
                                                        .height(66.dp)
                                                        .width(80.dp)
                                                        .clickable {
                                                            // TODO: 点击选择上传图片

                                                            launcher.launch("image/*")
                                                            currentSelectedImageForWho =
                                                                index * 2
                                                        })
                                            } else {
                                                AsyncImage(model = ApiService.BASE_URL + rectificationTask.picture.value,
                                                    contentDescription = "工地整改前的图片",
                                                    modifier = Modifier
                                                        .size(50.dp)
                                                        .clickable {
                                                            ifShowLargeImage.value = true
                                                            largeImageUrl =
                                                                ApiService.BASE_URL + rectificationTask.picture.value
                                                        })
                                            }

                                            Divider()
                                            Text(
                                                text = "整改后的图片:", fontSize = 14.sp,
                                                modifier = Modifier.padding(4.dp)
                                            )

                                            if (rectificationTask.pictureEnd.value.isEmpty()) {
                                                Icon(imageVector = Icons.Default.Photo,
                                                    tint = Color.Gray,
                                                    contentDescription = "点击本地选择图片上传",
                                                    modifier = Modifier
                                                        .height(66.dp)
                                                        .width(80.dp)
                                                        .clickable {
                                                            // TODO: 点击选择上传图片
                                                            launcher.launch("image/*")
                                                            currentSelectedImageForWho =
                                                                index * 2 + 1
                                                        })
                                            } else {
                                                AsyncImage(model = ApiService.BASE_URL + rectificationTask.pictureEnd.value,
                                                    contentDescription = "工地整改后的图片",
                                                    modifier = Modifier
                                                        .size(50.dp)
                                                        .clickable {
                                                            ifShowLargeImage.value = true
                                                            largeImageUrl =
                                                                ApiService.BASE_URL + rectificationTask.picture.value
                                                        })
                                            }
                                        }
                                    }
                                }

                                LazyVerticalGrid(
                                    columns = GridCells.Fixed(2),
                                    modifier =
                                    Modifier
                                        .height(70.dp)
                                        .padding(10.dp)
                                        .clip(RoundedCornerShape(6.dp))
                                        .background(Color.White),
                                ) {
                                    item {
                                        Box(
                                            modifier = Modifier.height(50.dp),
                                            contentAlignment = Alignment.CenterStart
                                        ) {
                                            Text(text = "其它:")
                                        }
                                    }
                                    item {
                                        Checkbox(checked = ifHaveOtherReason, onCheckedChange = {
                                            ifHaveOtherReason = it
                                        })
                                    }
                                }

                                var otherReasonValue by remember {
                                    mutableStateOf(task?.bz ?: "")
                                }

                                if (ifHaveOtherReason) {
                                    TextField(
                                        value = otherReasonValue,
                                        onValueChange = {
                                            if (task != null) {
                                                task.bz = it
                                            }
                                            otherReasonValue = it
                                        },
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(10.dp),
                                        placeholder = {
                                            Text(
                                                text = "请输入其它原因",
                                                fontWeight = FontWeight.Light
                                            )
                                        })
                                }

                                if ((task?.state ?: 0) == 0) {
                                    Button(
                                        onClick = {
                                            // TODO: 点击整改该项
                                            // 校验，要么选了一项，要么填了其它
                                            var canSubmit = false
                                            val selectItemIdArr = arrayListOf<Int>()
                                            val selectItemPictureArr = arrayListOf<String>()
                                            val selectItemPictureArrForEnd = arrayListOf<String>()
                                            RectificationTasks.defineTask.forEach {
                                                if (it.picture.value.isNotEmpty() && it.pictureEnd.value.isNotEmpty()) {
                                                    canSubmit = true
                                                    selectItemIdArr.add(it.id)
                                                    selectItemPictureArr.add(it.picture.value)
                                                    selectItemPictureArrForEnd.add(it.pictureEnd.value)
                                                }
                                            }

                                            if (ifHaveOtherReason && otherReasonValue.isNotEmpty()) {
                                                canSubmit = true
                                            }

                                            if (canSubmit) {
                                                // TODO: 提交整改内容
                                                if (task != null) {
                                                    task.cy = selectItemIdArr.joinToString(",")
                                                    task.purl =
                                                        selectItemPictureArr.joinToString(",")
                                                    task.purlEnd =
                                                        selectItemPictureArrForEnd.joinToString(",")
                                                    task.bz = otherReasonValue

                                                    val simpleDateFormat =
                                                        SimpleDateFormat("yyyy-mm-dd HH:MM:ss")
                                                    task.endime = simpleDateFormat.format(Date())

                                                    taskViewModel.updateTask(task)
                                                }
                                            } else {
                                                Toast.makeText(
                                                    this@RectificationResultsActivity,
                                                    "必须勾选一个原因并上传图片或者填写其它原因",
                                                    Toast.LENGTH_SHORT
                                                ).show()
                                            }

                                        }, modifier = Modifier.align(Alignment.CenterHorizontally),
                                        colors = ButtonDefaults.buttonColors(
                                            containerColor = Color(0, 179, 98)
                                        )
                                    ) {
                                        Text(text = "提交")
                                    }
                                }
                            }

                        }
                    }

                }
            }
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (ifShowLargeImage.value) {
            ifShowLargeImage.value = false

        } else {
            super.onBackPressed()
        }
    }
}
